<?php

namespace common\logics;

use common\helpers\ArrayHelper;
use Yii;
use yii\db\Exception;
use common\models\trend\TrendLog;
use common\models\user\UserTrend;
use common\models\user\UserTask;
use common\models\trend\TrendRule;
use common\models\BaseUser;
use common\models\order\Order;
use common\models\user\UserAccount;

/**
 * 奖励逻辑模型
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class RewardLogic extends \common\base\Model
{

    /**
     * 分享奖励
     *
     * @param Order $order
     * @return bool|void
     * @throws \yii\base\InvalidConfigException
     */
    public static function share($user_id)
    {
//        $name = 'share' . $order->model;
        $credit = ArrayHelper::getValue(Yii::$app->params, ['credit', 'share'], 0);
        return static::handler($user_id, 'share', $credit);
    }

    /**
     * 规则奖励
     *
     * @param integer $uid
     * @param string $name
     * @param integer|null $value
     * @return bool|void
     * @throws \yii\base\InvalidConfigException
     */
    public static function handler($uid, $name, $value = null)
    {
        $user = BaseUser::findIdentity($uid);
        if (!$user) {
            return;
        }

        $num = $value;

        $transaction = Yii::$app->db->beginTransaction();
        try {


            $account = new AccountBalanceLogic();
            $account->attributes = [
                'value' => $num,
                'type' => UserAccount::TYPE_CREDIT,
                'balance' => AccountBalanceLogic::BALANCE_IN,
                'user_id' => $uid,
                'mark' => '分享加贡献值',
            ];
            if (!$account->save()) {
                throw new Exception('账户积分更新失败');
            }

            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            Yii::error($e->getMessage());
            return false;
        }
        return true;
    }

}
